package com.roy.netty.epoll;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.SocketAddress;
import java.nio.charset.Charset;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/7
 * @description:
 **/

public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final SocketAddress socketAddress = ctx.channel().remoteAddress();
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("client "+socketAddress+" send message "+buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        final ChannelFuture channelFuture = ctx.writeAndFlush(Unpooled.copiedBuffer("你好 客户端。已经收到你的消息", Charset.forName("utf-8")));
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("消息已经回复给客户端");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常："+cause.getMessage());
        ctx.close();
    }
}
